# # import hashlib
# #
# #
# # def hash_string(input_string, hash_function=hashlib.sha256):
# #     hash_obj = hash_function()
# #     hash_obj.update(input_string.encode('utf-8'))
# #     hash_value = hash_obj.hexdigest()
# # #     return hash_value
# # #
# # #
# # # # 示例用法
# # # input_string = "中"
# # # md5_hash = hash_string(input_string, hashlib.md5)
# # # sha256_hash = hash_string(input_string)  # 默认为sha256
# # #
# # # print(f"MD5哈希值: {md5_hash}")
# # # print(f"SHA-256哈希值: {sha256_hash}")
# # # import time
# # #
# # # # 获取当前时间的时间戳（秒级）
# # # timestamp = time.time()
# # #
# # # import time
# # #
# # #
# # # microseconds = time.time() * 1e6
# # # microseconds_int = str(int(time.time()*1e6))[0:15]
# # # # print(microseconds_int)
# import time
# import  datetime
# import pytz
# a=int(str(int(time.time()))[0:10])
# print(a)
# b=datetime.datetime.fromtimestamp(a, tz=pytz.utc)
# china_tz = pytz.timezone('Asia/Shanghai')
# c=b.astimezone(china_tz)
#
#
# print(c)
# today = datetime.date.today()
#
# # 获取今天是周几（0表示周一，6表示周日）
# weekday_number = today.weekday()
#
# # 将数字转换为对应的星期名称
# weekdays = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
# weekday_name = weekdays[weekday_number]
#
# print(f"今天是{weekday_name}")
# print(weekday_number)
# one_hour = datetime.timedelta(hours=8)
# print(one_hour)
# new_timestamp = int(c.timestamp())
# print(new_timestamp)
#
# from datetime import datetime, timedelta
# def get_current_week_timestamps():
#     # 获取当前时间
#     now = datetime.now()
#
#     # 计算本周的周一和周日
#     start_of_week = now - timedelta(days=now.weekday())  # 周一
#     end_of_week = start_of_week + timedelta(days=6)  # 周日
#
#     # 转换为时间戳
#     start_timestamp = int(start_of_week.timestamp())
#     end_timestamp = int(end_of_week.timestamp()) + 86399  # 加上一天的秒数减一（为了包含当天的最后一秒）
#     #
#     # 获取周一到周日每天的时间戳
#     week_timestamps = {
#         'mon': int((start_of_week).timestamp()),
#         'tue': int((start_of_week + timedelta(days=1)).timestamp()),
#         'wed': int((start_of_week + timedelta(days=2)).timestamp()),
#         'thu': int((start_of_week + timedelta(days=3)).timestamp()),
#         'fri': int((start_of_week + timedelta(days=4)).timestamp()),
#         'sat': int((start_of_week + timedelta(days=5)).timestamp()),
#         'sun': int((start_of_week + timedelta(days=6)).timestamp())
#     }
#
#     # 如果需要周一的开始和周日的结束时间戳，可以返回这两个值和一个字典
#     return (start_timestamp, end_timestamp), week_timestamps
#
#
# # 使用函数
# (start_of_week_ts, end_of_week_ts), daily_ts = get_current_week_timestamps()
#
# print(f"本周的时间戳范围（开始到结束，包含整天）：{start_of_week_ts} 到 {end_of_week_ts}")
# print("每天的时间戳：")
# for day, ts in daily_ts.items():
#     print(f"{day}: {ts}")
from datetime import datetime, timedelta, timezone

import uvicorn
from fastapi import FastAPI
from sqlalchemy import text

from Model.default import SessionLocal


# WEEKDAY_=['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
# for i in WEEKDAY_:
    # print(i)

# def get_time_long_data(day,user_id):
#     session = SessionLocal()
#     update_stmt= text(f"SELECT {day} FROM user_behavior WHERE user_id = :user_id")
#     a=session.execute(update_stmt, {'user_id': user_id}).first()
#     session.commit()
#     session.close()
#     return a[0]
# print(get_time_long_data('mon',88888888))
#
# TIME_SPAN={
#     '0~4':'fn1','5~9':'fn2','10~14':'fn3','15~19':'fn4','20~24':'fn4'
# }
# # print(TIME_SPAN.get('0~4'))
# def deal_time_span(time):
#     ranges = {
#         '0~4': range(0, 5),
#         '5~9': range(5, 10),
#         '10~14': range(10, 15),
#         '15~19': range(15, 20),
#         '20~24': range(20, 25)
#     }
#
#     for range_span, rng in ranges.items():
#         print(rng)
#         if time in rng:
#             return TIME_SPAN.get(range_span)
# print(deal_time_span(datetime.now().hour))
# data={
#     "long": {
#     "mon_l": 0,
#     "tue_l": 0,
#     "wed_l": 42948,
#     "thu_l": 2270,
#     "fri_l": 0,
#     "sat_l": 0,
#     "sun_l": 0
#   },
#     "count": {
#     "fn1_c": 0,
#     "fn2_c": 11,
#     "fn3_c": 102,
#     "fn4_c": 32,
#     "fn5_c": 10
#   },
#   "处理方案": "一天时长分为5个时段，每个时段的次数对应fnx_c,mon_l对应每周在线时长,s为单位，请分析用户使用情况"
# }
#
# pre_Data=''
# for m,n in data.items():
#     if str(type(n))=="<class 'dict'>":
#         for i,j in n.items():
#             pre_Data+=str(i)+':'+str(j)+','
#     else:
#         pre_Data+=str(n)+','
# print(pre_Data)
# import re
#
# # 输入字符串
# url_string = "http://localhost:8000/index/blog/life_data/send_file/88888888173764386111977550?type=video,_,http://localhost:8000/index/blog/life_data/send_file/88888888173764386977750?type=video,_,"
#
# # 使用正则表达式根据,_,进行切割，并提取每个部分中的数字ID
# pattern = r'/send_file/(\d+)'
# matches = re.findall(pattern, url_string)
#
# # 打印提取的数字ID
# for match in matches:
#     print(match)
# import random
#
# print(random.randint(1, 10))
#
# import os
#
# # 获取当前文件的绝对路径
# current_file_abspath = os.path.abspath(__file__)
#
# # 获取当前文件所在目录的上级目录的绝对路径
# parent_directory_abspath = os.path.dirname(os.path.dirname(current_file_abspath))
#
# # 拼接目标文件路径
# target_file_path = os.path.join(parent_directory_abspath, 'Admin', 'static', 'dist', 'index.html')
# # print(target_file_path)
# import re
#
#
# def count_paragraphs_in_string(input_string):
#     # 使用正则表达式匹配任意的换行符号，并考虑段落间可能存在的多个空行
#     # \r?\n 匹配 Windows 的 \r\n 或 Unix/Linux/macOS 的 \n
#     # {2,} 表示前面的模式至少出现两次，即至少有两个换行符表示一个段落间隔
#     paragraphs = re.split(r'(?:\r?\n){2,}', input_string)
#
#     # 去除空段落和仅包含空白字符的段落
#     paragraphs = [p.strip() for p in paragraphs if p.strip()]
#
#     # 返回有效段落的数量
#     return len(paragraphs)
#
#
# # 示例字符串（包含不同系统的换行符号和多余的空行）
# input_string = """这是第一段。    \n
# 这是第二段。   \r\n\r\n        它包含更多的文字来描述这个段落。\n\n\n
# 这是第三段，只有一行。\n\n\n\n这是不存在的段落，因为它前面有多个空行。"""
#
# # 计算段落数量
# paragraph_count = count_paragraphs_in_string(input_string)
# print(f"字符串中的有效段落数量: {paragraph_count}")

# import matplotlib.font_manager as fm
#
# # 获取系统中所有字体
# font_list = fm.findSystemFonts(fontpaths=None, fontext='ttf')
#
# # 打印每个字体的路径
# for font in font_list:
#     print(font)
#
# import datetime
# import random
#
# print(str(random.uniform(0,1))[2:6])
# print(int(datetime.datetime.now().timestamp()))
import os
# import random
# import string
#
# def generate_verification_code(length=5):
#     characters = string.ascii_letters + string.digits
#     verification_code = ''.join(random.choice(characters) for _ in range(length))
#     return verification_code
#
#
# print(generate_verification_code())from fastapi import FastAPI, Depends, HTTPException, status, Cookie, Request
# from fastapi.security import HTTPBearer
# from fastapi.routing import APIRoute
#
# app = FastAPI()
#
# # 定义认证依赖
# async def get_token_from_cookie(access_token: str = Cookie(None)):
#     if not access_token:
#         raise HTTPException(
#             status_code=status.HTTP_401_UNAUTHORIZED,
#             detail="Not authenticated",
#             headers={"WWW-Authenticate": "Bearer"},
#         )
#     return access_token
#
# # 需要认证的路由
# protected_routes = {
#     "/protected-route",
#     "/admin",
#     "/user/profile",
# }
#
# # 全局依赖：自动为特定路由添加认证
# def auth_middleware(request: Request):
#     if request.url.path in protected_routes:
#         return Depends(get_token_from_cookie)
#     return None
#
# # 应用到所有路由
# app.dependency_overrides[APIRoute] = lambda route: APIRoute(
#     path=route.path,
#     endpoint=route.endpoint,
#     dependencies=[auth_middleware] + (route.dependencies or []),
#     **route.__dict__,
# )
#
# # 示例路由（不需要手动写 Depends）
# @app.get("/protected-route")
# async def protected_route(token: str = Depends(get_token_from_cookie)):
#     return {"message": "Authenticated!", "token": token}
#
# # 公开路由（不需要认证）
# @app.get("/public")
# async def public_route():
#     return {"message": "This is public!"}

async def get_token_from_cookie(access_token: str = Cookie(None)):
    if not access_token:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Not authenticated",
            headers={"WWW-Authenticate": "Bearer"},
        )
    return access_token

# 需要认证的路由
protected_routes = {
    "/protected-route",
    "/admin",
    "/user/profile",
}

# 全局依赖：自动为特定路由添加认证
def auth_middleware(request: Request):
    if request.url.path in protected_routes:
        return Depends(get_token_from_cookie)
    return None

# 应用到所有路由
app.dependency_overrides[APIRoute] = lambda route: APIRoute(
    path=route.path,
    endpoint=route.endpoint,
    dependencies=[auth_middleware] + (route.dependencies or []),
    **route.__dict__,
)

